package cn.itcast.order.quartz;

import cn.itcast.order.mapper.JobMapper;
import cn.itcast.order.pojo.Job;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.List;

@Component
@Slf4j
public class JobScheduler /*implements CommandLineRunner */{

    @Autowired
    private JobMapper jobMapper;
    @Autowired
    private Scheduler scheduler;

    /*@Override*/
    @Scheduled(fixedRate = 5000)
    public void run() throws Exception {
        List<Job> jobInfoList = jobMapper.findAll();
        for (Job jobInfo : jobInfoList) {
            JobDetail jobDetail = createJobDetail(jobInfo);
            Trigger trigger = createTrigger(jobInfo, jobDetail);
            try {
                scheduler.scheduleJob(jobDetail, trigger);
            }catch (SchedulerException se) {
                if (!(se instanceof ObjectAlreadyExistsException)) {
                    throw se;
                }
            }

        }
    }

    private JobDetail createJobDetail(Job jobInfo) throws ClassNotFoundException {
        JobDetailFactoryBean factory = new JobDetailFactoryBean();
        factory.setJobClass((Class<? extends org.quartz.Job>) Class.forName(jobInfo.getJobName()));
        factory.setDurability(true);
        factory.setGroup(jobInfo.getGroup());
        factory.setName(jobInfo.getJobName());
        factory.afterPropertiesSet();
        return factory.getObject();
    }

    private Trigger createTrigger(Job jobInfo, JobDetail jobDetail) throws ParseException {
        CronTriggerFactoryBean factory = new CronTriggerFactoryBean();
        factory.setJobDetail(jobDetail);
        factory.setCronExpression(jobInfo.getCorn());
        factory.setGroup(jobInfo.getGroup());
        factory.setName(jobInfo.getJobName());
        factory.afterPropertiesSet();
        return factory.getObject();
    }
}